<template>
  <div class="uploader">
    <el-form>
      <!-- :on-change="uploadFile" -->
      <el-upload
        :limit="limit"
        action
        :accept="accept"
        :http-request="uploadFile"
        list-type="picture-card"
        :auto-upload="true"
        :file-list="fileList"
        :on-exceed="handleExceed"
        :show-file-list="showFileList"
        ref="upload"
        class="avatar-uploader"
        :class="{hide:hideUpload}"
        multiple
      >
        <!--        :on-preview="handlePictureCardPreview"-->
        <!--        :before-remove="handleBeforeRemove"-->
        <!--        <template v-slot:tip>-->
        <!--          <slot name="tip"></slot>-->
        <!--        </template>-->
        <div class="el-upload__text">
          <em><i class="el-icon-plus"></i></em>
          {{accept}}
        </div>
        <div class="uploadImg" slot="file" slot-scope="{file}">
          <img :src="file.url" alt="" class="img" :ref='"file_"+file.uid' >
          <span class="el-upload-list__item-actions">
                <span class="el-upload-lists__item-preview" @click="handlePictureCardPreview(file)"><i class="el-icon-zoom-in"></i></span>
                <span class="el-upload-lists__item-delete" @click="handleBeforeRemove(file,fileList)"><i class="el-icon-delete"></i></span>
                <span class="el-upload-lists__item-rotate" @click="downImg(file.url,file)"><i class="el-icon-download"></i></span>
              </span>
        </div>
      </el-upload>
      <!--      <el-progress style="width: 240px;" v-show="progress > 0" :percentage="progress"-->
      <!--                   :status="uploadStatus"></el-progress>-->
      <el-dialog title="图片预览" width="30%" append-to-body :visible.sync="dialogVisible">
        <img width="100%" :src="previewUrl" alt/>
      </el-dialog>
    </el-form>
  </div>
</template>

<script>

import {upload_file} from "../../util/qinnu_upload";
import FileSaver from "file-saver"
export default {
  name: "file-uploader",
  props: {
    limit: Number,
    fileList: {
      type: Array,
      default: function () {
        return []
      }
    },
    showFileList: {
      type: Boolean,
      default: function () {
        return true
      }
    },
    accept: {
      type: String,
      default: 'image/*'
    },
    uplodParame:String

  },
  data() {
    return {
      hideUpload: false, //控制limit最大值之后 关闭上传按钮
      uploading: false,
      progress: 0,
      uploadStatus: 'warning',
      uploadedCount: 0,
      previewUrl: '',
      dialogVisible: false, //查看图片弹出
    };
  },
  //监听上传图片的数组(为了处理修改时,自动渲染问题,和上传按钮消失问题);
  watch: {
    fileList(newName, oldName) {
      // debugger
      if (newName.length >= this.limit) this.hideUpload = true;
      else this.hideUpload = false;
      this.uploadedCount = newName.length
    },
    uplodParame(newVal,oldVal){
      console.log(newVal)
      console.log(oldVal)
    }
  },
  methods: {
    downImg(url,file){
      var filename = ''
      if (file.name !=''){
        filename =file.name;
      }else{
        filename =file.uid;
      }
      var urltype = url.split('.')
      console.log(urltype[urltype.length - 1])
      const promise = this
        .downloadUrlQiniu(
          url
        )
        .then((res) => {
          var blob = new Blob([res]);
          FileSaver.saveAs(
            blob,
            filename +'.'  + urltype[urltype.length - 1]
          );
        })
        .catch((error) => {
          console.log(error)
        });
    },
    downloadUrlQiniu(url) {
      return new Promise((resolve, reject) => {
        if (!url.startsWith("http")) {
          return;
        }
        if (!url.startsWith("https")) {
          let urlArr = url.split("://");
          if (urlArr.length < 2) {
            return;
          }
          url = "https://" + urlArr[1];
        }
        // url = getCrossUrl(url)
        fetch(url, {
          method: "GET",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
          },
        })
          .then((res) => {
            resolve(res.blob());
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    reset() {
      this.progress = 0
      this.uploadStatus = 'warning'
      this.uploading = false
      if (this.fileList.length >= this.limit)
        this.hideUpload = true;
      else
        this.hideUpload = false;
    },

    //文件列表移除文件时的函数
    handleBeforeRemove(file, theFileList) {
      let parentSelf = this
      const result = new Promise((resolve, reject) => {
        let self = parentSelf
        this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const index = self.fileList.findIndex((item) => item.uid === file.uid);
          console.log("const index:" + index)
          self.fileList.splice(index, 1);
          self.uploadedCount--
          self.$emit("fileDeleted", self.fileList,self.uplodParame);
          self.reset()
          if (self.fileList.length < self.limit) self.hideUpload = false;
        }).catch(() => {
          this.$message.info(`已取消删除`);
          reject(false)
        });
      })
      return result
    },
    //点击文件列表中已上传的文件时的函数
    handlePictureCardPreview(file) {
      this.previewUrl = file.url;
      this.dialogVisible = true;
    },
    //这里是不需要直接上传而是通过按钮上传的方法
    submitUpload() {
      this.$refs.upload.submit();
    },
    //文件状态改变时的函数(主要逻辑函数)
    uploadFile(file) {
      if (this.uploadedCount >= this.limit) {
        this.hideUpload = true
        this.$message.warning(`上传图片数量不能大于${this.limit}`);
        return
      }
      this.reset()
      this.uploadedCount++
      //判断用户上传最大数量限制,来让上传按钮消失
      if (this.uploadedCount >= this.limit) {
        this.hideUpload = true
      }
      if (this.limit == 1) this.imgUrl = [];//此处判断为一张的时候需要清空
      this.uploading = true
      upload_file(file, this.handleProgress, this.handleCompleted, this.handleError)
      // }
    },
    handleProgress(percent) {
      this.progress = parseInt(percent)
    },
    handleError(error) {
      this.uploadStatus = 'exception'
      this.$message.warning(`上传图片失败：${error}`);
    },
    handleCompleted(upload_file, url) {
      console.log(upload_file)
      this.uploading = false
      this.uploadStatus = 'success'
      this.fileList.push({uid: upload_file.file.uid, url: url,name:upload_file.file.name})
      console.log("uploadFinished:" + url)
      this.$emit("uploadFinished", url,this.uplodParame);
    },
    //文件超出个数限制时的函数
    handleExceed(file, file_list) {
      this.$message.info(`最多只允许上传${this.limit}张图片`);
    },
  },
};
</script>


//这里修改上传前后的样式(我觉得el-upload不好看 也可以自行修改)
<style scope lang="scss">

.hide .el-upload--picture-card {
  display: none !important;
}
.avatar-uploader > .el-upload {
  width: 120px;
  height: 120px;
  line-height: 30px;
  border-radius: 0px;
  background: #fff;
  border: 1px dashed #ccc;
  display: flex;
  align-items: center;

}

.avatar-uploader > .el-upload > i {
  font-size: 28px;
  color: #ccc;
}

.avatar-uploader > .el-upload-list {
  display: flex;
  flex-wrap: wrap;
}

.avatar-uploader > .el-upload-list > .el-upload-list__item {
  width: 120px;
  height: 120px;
  display: block;
}
.avatar-uploader > .el-upload .el-upload__text {
  color: #ccc;
}
.avatar-uploader > .el-upload-list > .el-upload-list__item > img {
  width: 120px;
  height: 120px;
  border-radius: 0px;
}
.uploadImg{
  width: 120px;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
  img{
    max-width: 120px;
    max-height: 120px;
  }
}

</style>


